package com.atwu.wl2022.service.impl;

import com.atwu.wl2022.entity.User;
import com.atwu.wl2022.mapper.UserMapper;
import com.atwu.wl2022.service.IUserService;
import com.atwu.wl2022.service.MailService;
import com.atwu.wl2022.util.UUIDUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;


/**
 * <p>
 * 这是用户信息表
 * </p>
 *
 * @author wule
 * @since 2022-06-12
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	@Autowired
	UserMapper userMapper;
	@Autowired
	MailService mailService;

	@Override
	public User checkCode(String code) {
		return userMapper.checkCode(code);
	}

	@Override
	public void updateUserStatus(User user) {
		userMapper.updateUserStatus(user);
	}

	@Override
	public User retrieve(String email) {
		return userMapper.retrieve(email);
	}

	/**
	 * 用户注册，同时发送一封激活邮件
	 *
	 * @param user 封装的用户信息
	 */
	@Override
	public boolean register(User user) {
		User userByUserName = userMapper.getUserByUserName(user.getUserName());
		if (userByUserName != null) {
			log.error("注册失败，原因：《注册账号重复》");
			return false;
		}
		userMapper.register(user);
		String code = user.getCode();
		log.info("用户激活码code:{}", code);
		String subject = "来自wl2022网站的激活邮件";
		///checkCode?code=xxx即是我们点击邮件链接之后进行更改状态的
		String context = "<h1>此邮件为官方激活邮件！请点击下面链接完成激活操作！</h1> <a href=\"http://47.115.229.171:5527/selectCode?code=" + code + "\">激活请点击:" + code + "</a> ";
		//发送激活邮件
		mailService.sendHtmlMail(user.getEmail(), subject, context);
		return true;

	}

	@Override
	public String  sendCaptcha(String email) {
		String captcha = UUIDUtils.CAPTCHA(4);
		String subject = "来自wl2022网站的官方邮件";
		String context = "<h1>校验码："+captcha+ "</h1> <a>注意！提交一次后验证码失效，如果未验证成功，需重新发送<a>";
		//邮件
		mailService.sendHtmlMail(email, subject, context);
		return captcha;
	}
}
